<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>购物车</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <style>
        ul.list-group.list-group-1 {
            text-align: right;
            padding: 5px 30px 0 0;
            background: #eee;
        }
        li.list-group-item.list1 {
            display: inline-block;
            border: 0;
            background: #eee;
        }

        ul.list-group.list-group-1 a{
            color: #0e0e0e;

        }
        /******login弹出层样式****/

        .form{
            width: 350px;
            background-color: #fff;
            height: 220px;
            margin: 10px auto;
        }
        .form>div{
            position: relative;
            line-height: 100%;
            margin-bottom: 8px;
        }
        .form>div input{
            width: 100%;
            height: 35px;
            border-radius: 3px;
            border: 1px solid #ddd;
            text-indent: 40px;
        }
        .form>div label{
            position: absolute;
            left: 0;
            top:10px;
            width: 30px;
            text-align: right;
            color: #808080;
        }
        .form .yanzhengma input{
            width: 50%;
            text-indent: 10px;
        }
        .form .yanzhengma img{
            height: 30px;
            width: 75px;
            font-size: 0;
            vertical-align: middle;
        }
        .form .yanzhengma a{
            font-size: small;
            text-decoration: none;
            color: #00a5e0;
        }
        .form>div.chk label{
            width: 100px;
            padding-left: 20px;
        }
        .form>div.chk input{
            width: 22px;
            height: 22px;
            margin-top: 8px;
        }
        .form>div.chk a{
            float: right;
            margin-top: 9px;
            text-decoration: none;
            color: #00a5e0;
        }
        .buts button{
            width: 48%;
            float: left;
        }
        .buts button:first-child{
            margin-right: 4%;
        }
        /************login弹出层样式结束********************/
    </style>
    <style>
        .container {
            background: cornsilk;
        }
        .red-font{
            color: #c63205;
            font-size: 16px;
            margin: 0 5px;
        }
        hr{
            margin: 0;
        }
        /***************************/
        .table>tbody>tr>th{
            border-top:0;
            text-align: center;
        }
        .table>tbody>tr>td{
            position: relative;
            text-align: center;
            border-bottom: 1px solid #ddd;
        }
        .table>tbody>tr>td:first-child{
            border-left: 1px solid #ddd;
        }
        .table>tbody>tr>td:last-child{
            border-right: 1px solid #ddd;
        }
        table tr td img{
            width: 100%;
        }
        .checkbox-row{
            display: inline-block;
            position: relative;
        }
        .ls-checkbox {
            display: inline-block;
            width: 25px;
            height: 25px;
            opacity: 0;
            z-index: 100000;
        }
        .ls-checkbox + label {
            background-color: #99a1a7;
            border: 1px solid #cacece;
            padding: 10px;
            border-radius: 3px;
            display: inline-block;
            position: absolute;
            top: 5px;
            left: 1px;
        }
        .ls-checkbox:checked + label {
            background-color: #fff;
            border: 1px solid #adb8c0;
            color: #ffb723;
        }
        .ls-checkbox:checked + label:after {
            content: '\2714';
            font-size: 18px;
            position: absolute;
            top: -1px;
            left: 3px;
            color: #ffb723;
        }
        .jiesuan{
            height: 50px;
            background: #eee;
            margin: 50px 0;
        }
        .jiesuan .jiesuan-left{
            display: inline-block;
            width: 40%;
            padding-left: 25px;
            height: 50px;
            line-height: 50px;
        }
        .jiesuan .jiesuan-right{
            display: inline-block;
            text-align: right;
            width: 55%;
        }
        .jiesuan .jiesuan-right>span{
            margin:0 20px 0 10px;
        }
    </style>
</head>
<body>
<!--顶部导航-->
<ul class="list-group list-group-1" id="top-part">
    <li class="list-group-item list1"><a href="./index.jsp"><i class="fa fa-home"></i> 首页</a></li>
    <c:if test="${empty user }">
        <li class="list-group-item list1">登录【<a href="" data-toggle="modal" data-target="#myModalLogin" style="font-size: small;color:#e4393c ">请登录</a>】</li>
        </c:if>
            <li role="presentation" class="dropdown list-group-item list1">
                <c:if test="${!empty user }">
                <a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
                    <img src="${user.headImg }" style="border-radius: 50%;width: 25px;height: 25px;"/><b>${user.nickname }</b>
                </a>
                <ul class="dropdown-menu">
                    <li><a href="user.jsp">个人设置</a></li>
                    <li><a href="#">切换账号</a></li>
                    <li><a href="../logout">退出</a></li>
                </ul>
                <c:if test="${user.role == 1}">
            <li class="list-group-item list1"><a href="../backend/main.jsp"><i class="fa fa-cog"></i> 后台管理</a></li>
        </c:if>
    </c:if>

    </li>
    <li class="list-group-item list1"><a href="../myCartServlet"><span class="glyphicon glyphicon-shopping-cart" aria-hidden="true" style="color:#c63205"></span> 购物车</a></li>
    <li class="list-group-item list1"><a href="../selectOrder"><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> 我的订单</a></li>
</ul>
<div class="modal fade" id="myModalLogin" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">欢迎登陆</h4>
            </div>
            <div class="modal-body">
                <form action="../login.do" class="form">
                    <div class="name">
                        <label for="loginname"><span class="glyphicon glyphicon-user"></span></label>
                        <input type="text" placeholder="用户名" id="loginname"  name="loginname">
                    </div>
                    <div class="password">
                        <label for="pwd"><span class="glyphicon glyphicon-lock"></span></label>
                        <input type="password" placeholder="请输入密码"  id="pwd" name="pwd">
                    </div>
                    <div class="yanzhengma">
                        <input type="text" placeholder="输入验证码"  id="yanzhengma" name="yanzhengma" width="50%">
                        <img src="images/yanzhengma.JPG" alt="" height="35" width="80">
                        <a href="#">换一张</a>
                    </div>
                    <div class="chk">
                        <label for="ch1" width="60px">10天免登陆</label>
                        <input type="checkbox" id="ch1">
                        <a href="register.jsp">免费注册</a>
                    </div>
                    <div class="buts">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-success">登陆</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<hr class="divider">
<!--主体内容-->
<div class="container">
    <table class="table" style="margin-top: 10px">
        <table class="table" style="margin-top: 10px">
            <tbody>
            <tr>
                <th colspan="4">商品信息</th>
                <th>单价（元）</th>
                <th>数量</th>
                <th>金额（元）</th>
                <th>操作</th>
            </tr>
            <c:if test="${empty myCartList}">
                <tr>
                    <td colspan="8" style="text-align: center;">空空如也</td>
                </tr>
            </c:if>
            <c:if test="${!empty myCartList}">
                <c:forEach var="list" items="${myCartList}">
                    <tr data-quantity="${list.qty }" data-amount="${list.cartSum }">
                        <td class="col-sm-1 clickable-cell">
                            <br>
                            <div class="checkbox-row">
                                <input type="checkbox" class="ls-checkbox" id="chk_${list.cartId}" name="chkgoods">
                                <label for="chk_${list.cartId }"></label>
                            </div>
                        </td>
                        <td class="col-sm-1">
                            <img src="${list.goodsImage }" alt="">
                            <span class="cardId" style="display: none;">${list.cartId }</span>
                            <span class="quantity" style="display: none;">${list.qty }</span>
                        </td>
                        <td><br>${list.goodsName }</td>
                        <td><br>${list.note }</td>
                        <td><br>单价：${list.goodsPrice }</td>
                        <td><br>数量：${list.qty }</td>
                        <td><br>总额：${list.cartSum }</td>
                        <td><br><span class="glyphicon glyphicon-trash red-font" data-cart-id="${list.cartId}" onclick="showDeleteConfirmModal(this)"></span></td>
                        </td>
                        </td></td>
                    </tr>
                    <tr>
                        <th></th>
                    </tr>
                </c:forEach>
            </c:if>
            </tbody>
        </table>
    </table>
</div>
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" role="dialog" aria-labelledby="deleteConfirmModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="deleteConfirmModalLabel">确认删除</h4>
            </div>
            <div class="modal-body">
                你确定要删除这项商品吗？
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
            </div>
        </div>
    </div>
</div>
<div class="container" style="background: #fff; padding: 0">
    <div class="jiesuan">
        <div class="jiesuan-left" >
            <input type="checkbox" id="checkall" class="checkall" onclick="allnone()">
            <span style="margin: 0 15px 0 5px">全选/全不选</span>
            <button type="button" class="btn btn-default" id="bulkDeleteBtn">删除</button>
        </div>
        <div class="jiesuan-right" >
            <span>已选商品<span class="red-font" id="selectQty">0</span>件</span>
            <span>总金额(不含运费)：¥<span class="red-font" id="selectSum">0.00</span>元</span>
            <button type="button" class="btn btn-danger" id="checkoutBtn">结算</button>
        </div>
    </div>
</div>


</body>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
    var loves=document.getElementsByName("chkgoods");
    var ckb1=document.getElementById("checkall");
    var j=0;
    function alls(){
        for(var i=0;i<loves.length;i++){
            var love1=loves[i];
            love1.checked=true;
        }
        ckb1.checked=true;
    }
    function none(){
        for(var i=0;i<loves.length;i++){
            var love1=loves[i];
            love1.checked=false;
        }
        ckb1.checked=false;
    }
    function allnone(){
        if(ckb1.checked==true){
            alls();
        }else{
            none();
        }
    }
    for(var i=0;i<loves.length;i++){
        var love1=loves[i];
        love1.onclick=function(){
            if(this.checked==true){
                j++;
                if(j==loves.length)
                    ckb1.checked=true;
            }else if(this.checked==false){
                j--;
                if(j!=loves.length)
                    ckb1.checked=false;
            }
        }
    }
</script>

<script>
    var cartIdToDelete = null;

    function showDeleteConfirmModal(element) {
        cartIdToDelete = element.getAttribute('data-cart-id');
        $('#deleteConfirmModal').modal('show');
    }

    function deleteCartItem() {
        if (cartIdToDelete) {
            // 发送AJAX请求到服务器以删除该项
            $.ajax({
                url: '../deleteCartById', // 你的Servlet的URL
                method: 'POST',
                data: {
                    cartId: cartIdToDelete
                },
                success: function(response) {
                    // 成功后，从表格中移除该行
                    var row = document.querySelector('span[data-cart-id="' + cartIdToDelete + '"]').closest('tr');
                    row.parentNode.removeChild(row);

                    // 更新选中的商品和总金额
                    updateSelectedItems();

                    // 隐藏模态框
                    $('#deleteConfirmModal').modal('hide');
                },
                error: function(xhr, status, error) {
                    console.error("删除失败: " + error);
                }
            });
        }
    }

    // 绑定确认删除按钮的点击事件
    document.getElementById('confirmDeleteBtn').addEventListener('click', deleteCartItem);


    document.getElementById('bulkDeleteBtn').addEventListener('click', function() {
        // 获取所有选中的复选框
        var checkedCheckboxes = document.querySelectorAll('input[name="chkgoods"]:checked');

        // 获取选中的复选框对应的 ID
        var selectedIds = [];
        checkedCheckboxes.forEach(function(checkbox) {
            var row = checkbox.closest('tr');
            var cartId = row.querySelector('.cardId').textContent.trim();
            selectedIds.push(cartId);
        });

        if (selectedIds.length > 0) {
            // 打开确认删除模态框
            $('#deleteConfirmModal').modal('show');

            // 点击确认删除按钮时的操作
            document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
                // 发送 AJAX 请求到服务器以删除选中的项目
                $.ajax({
                    url: '../deleteCarts', // 你的Servlet的URL
                    method: 'POST',
                    cache: false, // 禁用缓存
                    data: {
                        cartIds: JSON.stringify(selectedIds) // 将ID数组转为JSON字符串传递给服务器
                    },
                    success: function(response) {
                        window.location.reload(); // 刷新页面
                        selectedIds.forEach(function(cartId) {
                            var rowToDelete = document.querySelector('tr[data-quantity="' + cartId + '"]');
                            if (rowToDelete) {
                                rowToDelete.parentNode.removeChild(rowToDelete);
                            }
                        });

                        // 删除后更新选定的项目
                        updateSelectedItems();
                    },
                    error: function(xhr, status, error) {
                        console.error("删除失败: " + error);
                    }
                });
            });
        } else {
            alert('请选择要删除的商品。');
        }
    });

    var chkgoodsCheckboxes = document.querySelectorAll('input[name="chkgoods"]');
    var selectQtyElement = document.getElementById("selectQty");
    var selectSumElement = document.getElementById("selectSum");
    var checkAllCheckbox = document.getElementById("checkall");

    function updateSelectedItems() {
        var selectedCount = 0;
        var totalAmount = 0.00;

        chkgoodsCheckboxes.forEach(function(checkbox) {
            if (checkbox.checked) {
                var row = checkbox.closest('tr');
                var qty = parseInt(row.dataset.quantity);
                var amount = parseFloat(row.dataset.amount);

                selectedCount += qty;
                totalAmount += amount;
            }
        });

        selectQtyElement.innerText = selectedCount;
        selectSumElement.innerText = totalAmount.toFixed(2);
    }

    function updateCheckAll() {
        var allChecked = true;
        for (var i = 0; i < chkgoodsCheckboxes.length; i++) {
            if (!chkgoodsCheckboxes[i].checked) {
                allChecked = false;
                break;
            }
        }
        checkAllCheckbox.checked = allChecked;
    }

    // 初始加载时调用一次更新函数
    updateSelectedItems();

    // 绑定复选框的点击事件
    chkgoodsCheckboxes.forEach(function(checkbox) {
        checkbox.addEventListener("click", function() {
            updateSelectedItems();
            updateCheckAll();
        });
    });

    // 绑定全选按钮的点击事件
    checkAllCheckbox.addEventListener("click", function() {
        var isChecked = this.checked;
        chkgoodsCheckboxes.forEach(function(checkbox) {
            checkbox.checked = isChecked;
        });
        updateSelectedItems();
    });
</script>


<script>
    window.onload = function() {
        checkError();
    }
    function checkError() {
        var errorMsg = "${errorMsg}";
        var successMsg = "${successMsg}";
        if (successMsg){
            alert(successMsg);
            <% session.removeAttribute("successMsg"); %>
        }
        if (errorMsg) {
            alert(errorMsg);
            <% session.removeAttribute("errorMsg"); %>
        }
    }
</script>

<script>
    document.getElementById('checkoutBtn').addEventListener('click', function() {
        // 获取所有选中的复选框
        var checkedCheckboxes = document.querySelectorAll('input[name="chkgoods"]:checked');

        // 获取选中的复选框对应的 ID 和数量
        var selectedItems = [];
        checkedCheckboxes.forEach(function(checkbox) {
            var row = checkbox.closest('tr');
            var cartIdElement = row.querySelector('.cardId');
            var quantityElement = row.querySelector('.quantity');

            if (cartIdElement && quantityElement) {
                var cartId = cartIdElement.textContent.trim();
                var quantity = quantityElement.textContent.trim(); // 使用 textContent 获取数量
                selectedItems.push({ cartId: cartId, quantity: quantity });
            } else {
                console.error("无法找到 cartId 或 quantity 元素");
            }
        });

        if (selectedItems.length > 0) {
            // 发送 AJAX 请求到服务器以处理结算
            $.ajax({
                url: '../settleCartItems', // 你的Servlet的URL
                method: 'POST',
                contentType: 'application/json', // 设置请求内容类型为JSON
                data: JSON.stringify(selectedItems), // 将ID和数量数组转为JSON字符串传递给服务器
                success: function(response) {
                    if (response.message) {
                        window.location.href = './jiesuan2.jsp';
                    }
                },
                error: function(xhr, status, error) {
                    console.error("结算失败: " + error);
                }
            });
        } else {
            alert('请选择要结算的商品。');
        }
    });
</script>




</html>